package com.heima.article.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApCollectionService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class ApCollectionServiceImpl implements ApCollectionService {

    private final CacheService cacheService;
    /**
     * 收藏
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //1校验参数
        if (dto == null || checkParams(dto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //统一缓存键结构
        String cacheKey = BehaviorConstants.COLLECTION_BEHAVIOR +String.valueOf(user.getId());
        String userId = String.valueOf(dto.getEntryId());
        // 查询是否存在
        String existing = String.valueOf(cacheService.hGet(cacheKey, userId));
        //3.保存数据
        if (dto.getOperation() == 0){
            //判断是否已经收藏
            if (StringUtils.isNotBlank(existing)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已收藏");
            }
            // 原子操作：仅当字段不存在时写入
//            boolean success = cacheService.hSetNx(collectionKey, entryId, JSON.toJSONString(dto));
//            if (!success) {
//                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "操作冲突");
//            }
            log.info("收藏：保存key={}, userId={}, dto={}", cacheKey, userId, JSON.toJSONString(dto));
            cacheService.hPut(cacheKey, userId, JSON.toJSONString(dto));
        }else {
            // 取消收藏操作
            log.info("取消收藏：删除key={}, userId={}, dto={}", cacheKey, userId, JSON.toJSONString(dto));
            cacheService.hDelete(cacheKey, userId);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    /**
     * 校验参数
     * @param dto
     * @return
     */
    private boolean checkParams(CollectionBehaviorDto dto) {
        return dto.getEntryId() == null  || dto.getOperation() == null || dto.getOperation() <0 || dto.getOperation() >1;
    }
}
